<template>
  <div class="box">
    <el-card class="index-container">
      <template #header>
        <h1>我绑定的老人</h1>

        <div class="header">

          <div class="search-container">
            <el-input
                v-model="state.searchValue"
                placeholder="老人名称"
                clearable
                style="width: 300px; margin-right: 10px"
            />
            <el-button type="success" color="#71c4ef" @click="handleSearch">查询</el-button>
            <el-button type="success" color="#313d44" plain @click="handleReset">重置</el-button>
          </div>
          <div class="action-buttons">
            <el-button type="primary" color="#FF3D3D" :icon="Plus" @click="handleAdd">增加</el-button>
            <el-popconfirm
                title="确定要批量删除吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="AllDetele"
            >
              <template #reference>
                <el-button type="primary" color="red" size="size" style="margin-left: 8px">
                  批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </template>

      <el-table
          :load="state.loading"
          ref="multipleTable"
          :data="state.tableData"
          tooltip-effect="dark"
          style="width: 100%;"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55"
        >
        </el-table-column>
        <el-table-column
            label="序号"
            align="center"
            width="120"
        >
          <template #default="scope">
            {{ (state.currentPage - 1) * state.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column
            prop="elderlyName"
            label="名称"
            align="center"
        >
        </el-table-column>


        <el-table-column
            prop="gender"
            label="性别"
            align="center"
        >
        </el-table-column>


        <el-table-column
            prop="age"
            label="年龄"
            align="center"
        >
        </el-table-column>

        <el-table-column
            prop="phone"
            label="电话"
            align="center"
        >
        </el-table-column>

        <el-table-column
            prop="address"
            label="地址"
            align="center"
        >
        </el-table-column>
        <el-table-column
            label="功能"
            align="center"
        >
          <template #default="scope">
            <el-button
                type="warning"
                size="small"
                :icon="ZoomIn"
                @click="handleElderlyAdd(scope.row.id)">
              预测健康
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <div class="action-buttons">

              <!-- 编辑按钮 -->
              <el-button
                  type="warning"
                  size="small"
                  :icon="Edit"
                  :disabled="scope.row.id === '1'"
                  @click="handleEdit(scope.row.id)">
                编辑
              </el-button>

              <!-- 删除按钮（带确认） -->
              <el-popconfirm
                  title="确定要删除此项吗？"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  @confirm="handleDeleteOne(scope.row.id)"
              >
                <template #reference>
                  <el-button
                      type="danger"
                      size="small"
                      :icon="Delete"
                      :disabled="scope.row.id === '1'"
                      style="margin-left: 8px">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--总数超过一页，再展示分页器-->
      <el-pagination
          v-if="state.total > state.pageSize"
          background
          layout="prev, pager, next"
          :total="state.total"
          :page-size="state.pageSize"
          :current-page="state.currentPage"
          @@size-change="handleSizeChange"
          @current-change="changePage"
      />
    </el-card>
  </div>


  <el-dialog title="内容" v-model="fromVisible" width="50%">
    <div slot="footer" class="dialog-footer">
        <span>
          <el-button style="float: right" type="primary" @click="fromVisible =false">确 定</el-button>
        </span>
    </div>
  </el-dialog>


  <!--    编辑弹窗控件-->
  <MyElderlyDialog ref='infoClassify' :reload="getIndexConfig" :type=state.type
                   :configType="state.configType"/>

  <ElderlyAnalysis ref='Elderlymessage' :reload="getIndexConfig"/>
</template>


<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import MyElderlyDialog from '../client/MyElderlyDialog.vue'
import {useRoute, useRouter} from 'vue-router'
import {Delete, Edit, ZoomIn} from '@element-plus/icons-vue'
import {getElderlyInfo, ClientDeleteElderly, ClientbatchDelete} from '../../service/elderlyInfoApi.js'
import ElderlyAnalysis from '../client/ElderlyAnalysisDialog.vue'
// 首页配置类型参数
const configTypeMap = {
  hot: 3,
  new: 4,
  recommend: 5
}

const fromVisible = ref(false)
const router = useRouter()
const route = useRoute()
const multipleTable = ref(null)

const Elderlymessage = ref(null)
const infoClassify = ref(null)
const state = reactive({
  searchValue: '', // 新增搜索值
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 5, // 分页大小
  type: 'add', // 操作类型
  configType: 3, // 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐
  content: ''
})


// 监听路由变化
router.beforeEach((to) => {
  if (['hot', 'new', 'recommend'].includes(to.name)) {
    state.configType = configTypeMap[to.name]
    state.currentPage = 1
    getIndexConfig()
  }
})

// 初始化
onMounted(() => {
  state.configType = configTypeMap[route.name]
  getIndexConfig()
})

// 获取列表数据（添加搜索参数）
const getIndexConfig = async () => {
  state.loading = true
  const params = {
    pageNum: state.currentPage,
    pageSize: state.pageSize,
    elderlyName: state.searchValue
  }
  // 查询资讯分类列表数据
  const response = await getElderlyInfo(params);
  state.tableData = response.data.records || []
  state.total = response.data.total || 0
}

// 搜索处理
const handleSearch = () => {
  state.currentPage = 1
  getIndexConfig()
}

// 重置处理
const handleReset = () => {
  state.searchValue = ''
  getIndexConfig()
}

// 其他原有方法保持不变...
// 添加商品
const handleAdd = () => {
  state.type = 'add'
  infoClassify.value.open()
}
// 修改商品
const handleEdit = (id) => {
  console.log('handleEdit', id)
  state.type = 'edit'
  infoClassify.value.open(id)
}

const handleElderlyAdd = (id) => {
  Elderlymessage.value.open(id)
}

// 选择项
const handleSelectionChange = (val) => {
  state.multipleSelection = val

}

// 单个删除
const handleDeleteOne = (id) => {
  // 原有删除逻辑...
  ClientDeleteElderly(id).then(() => {
    ElMessage.success('删除成功')
    state.currentPage = 1
    getIndexConfig()
  })
}

// 分页处理
const changePage = (val) => {
  state.currentPage = val
  getIndexConfig()
}

// 每页条数变化
const handleSizeChange = (val) => {
  state.pageSize = val
  state.currentPage = 1
  getIndexConfig()
}

// 批量删除
const AllDetele = async () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项')
    return
  }
  const response = await ClientbatchDelete(state.multipleSelection.map(item => item.id));
  if (response.code === 200) {
    ElMessage.success('删除成功')
    state.currentPage = 1
    await getIndexConfig()
  } else {
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.box {
  text-align: center;

}

.index-container {
  display: inline-block;
  min-height: 100%;
  width: 80%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end; /* 将内容推到容器末尾 */
  align-items: center; /* 垂直居中 */
}
</style>
